package com.flow.framework.persistence.handler;

import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.holder.SecurityContextHolder;
import com.flow.framework.core.properties.FrameworkCoreConfigProperties;
import com.flow.framework.persistence.properties.FrameworkPersistenceConfigProperties;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

/**
 * 数据库租户处理类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/4/4
 */
@Slf4j
public class CustomizationTenantHandler implements TenantHandler {

    private FrameworkPersistenceConfigProperties frameworkPersistenceConfigProperties;

    private FrameworkCoreConfigProperties frameworkCoreConfigProperties;

    /**
     * 创建租户id处理器
     *
     * @param frameworkPersistenceConfigProperties 框架持久化配置
     * @param frameworkCoreConfigProperties 框架核心配置
     */
    public CustomizationTenantHandler(FrameworkPersistenceConfigProperties frameworkPersistenceConfigProperties,
                                      FrameworkCoreConfigProperties frameworkCoreConfigProperties) {
        this.frameworkPersistenceConfigProperties = frameworkPersistenceConfigProperties;
        this.frameworkCoreConfigProperties = frameworkCoreConfigProperties;
    }

    /**
     * @inheritDoc
     */
    @Override
    public Expression getTenantId(boolean where) {
        String tenantId = SecurityContextHolder.getTenantIdQuietly();
        if (VerifyUtil.isEmpty(tenantId)) {
            log.error("biz tenant id is empty");
            throw new CheckedException(SystemErrorCode.TENANT_ID_ERROR);
        }
        return new StringValue(tenantId);
    }

    /**
     * @inheritDoc
     */
    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    /**
     * @inheritDoc
     */
    @Override
    public boolean doTableFilter(String tableName) {
        if (null == frameworkCoreConfigProperties) {
            return true;
        }
        if (!frameworkCoreConfigProperties.isEnableTenantSupport()) {
            return true;
        }
        return frameworkPersistenceConfigProperties.getIgnoreTenantTableNames().contains(tableName);
    }
}
